package com.simou.controller;

import com.simou.pojo.Provider;
import com.simou.service.BillServiceImpl;
import com.simou.service.ProviderServiceImpl;
import com.simou.pojo.User;
//import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.simou.pojo.Bill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;

/*  处理用户相关请求，分为三个模块
    1. 路径转发
    2. AJAX请求
    3. 表单请求
*/

@Controller
public class BillController {

    @Autowired
    BillServiceImpl billService;

    @Autowired
    ProviderServiceImpl providerService;

/*  *****************************************************
    1. 路径转发
    *****************************************************
*/

    @RequestMapping("jsp/bill.do")
    public String selectMethod(String method) {
        System.out.println("method:" + method);
        switch (method) {
            case "query":
                return "forward:getBillList";
            case "add":
                return "forward:addBill";
            case "modify":
                return "forward:/bill/modify.do";
            case "modifysave":
                return "forward:modifyBill";
            case "pwdmodify":
                return "forward:verifyOldPassword";
            case "savepwd":
                return "forward:savepwd";
            case "view":
                return "forward:/bill/view";
            case "delbill":
                return "forward:delbill";
            case "getproviderlist":
                return "forward:getproviderlist";
            default:
                return "/";
        }
    }

/*  *****************************************************
    2. AJAX请求
    *****************************************************
*/

    //  2.1 根据billid填充被修改供应商的原信息
    @RequestMapping("bill/modify.do")
    public String modifyBill(String method,Integer billid,Model model,HttpSession session){
        System.out.println("method:"+method);
        System.out.println("billid:"+billid);
        System.out.println("modifyexe billid:"+billid);
        Object obj = session.getAttribute("billList");
        Object obj2 = session.getAttribute("providerList");
        if(obj!=null){
            List<Bill> billList = (List<Bill>) obj;
            for (Bill bill : billList) {
                if (bill.getId()==billid){
                    // 将用户信息发送给前端，前端自动填充用户的原数据
                    model.addAttribute("bill",bill);
                }
            }
        }
        if(obj2!=null){
            List<Provider> providerList = (List<Provider>) obj2;
            model.addAttribute("providerList",providerList);
        }
        return "billmodify";
//等同于 return "forward:/WEB-INF/jsp/billmodify.jsp";
//等同于 return "/billmodify";
    }

    //  2.2 删除订单
    @RequestMapping("/jsp/delbill")
    @ResponseBody
    public String deleteBill(String method,long billid) throws JsonProcessingException {
        System.out.println("删除用户 method："+method);
        System.out.println("删除用户 billid："+billid);
        int i = billService.deleteBill(billid);
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("delResult",i>0?"true":"false");
        System.out.println(i>0?"删除成功":"删除失败");
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(resultMap);
    }

//    2.3 获取供应商列表
    @RequestMapping("/jsp/getproviderlist")
    @ResponseBody
    public String getProviderList() throws JsonProcessingException {
        List<Provider> providerList = providerService.getProvidersByLimit(0, 9999, null, null);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(providerList);

    }

/*  *****************************************************
    3. 表单请求
    *****************************************************
*/

    //  3.1 查询用户信息
    @RequestMapping("jsp/getBillList")
    public String getBillList(Model model, String pageIndex, String queryProductName, String queryProviderId, String queryIsPayment,HttpSession session){
        System.out.println(queryProductName);
        System.out.println(queryProviderId);
        long prodiverId = 0;
        int isPayment = 0;
//        若queryProviderId不为空或null
        if(StringUtils.hasLength(queryProviderId)){
            prodiverId = Long.valueOf(queryProviderId);
        }
        if(StringUtils.hasLength(queryIsPayment)){
            isPayment = Integer.valueOf(queryIsPayment);
        }

        int pageSize = 5;
        int currentPageNo = 1;
        long billRole = 0l;
        if(StringUtils.hasLength(pageIndex)){
            currentPageNo = Integer.parseInt(pageIndex);
        }
        List<Provider> providerList = providerService.getProvidersByLimit(0, 9999, null, null);

        // 1.查询数据库中一共有多少个用户
        int totalCount = billService.getBillsCount(queryProductName,prodiverId,isPayment);

        // 2.查询用户信息（根据limit和检索条件）
//         起始 = (currentPageNo-1)*5      currentPageNo=1: limit 0,5 ;currentPageNo=2: limit 5,5
        List<Bill> billList = billService.getBillsByLimit((currentPageNo - 1) * 5, pageSize,queryProductName, prodiverId,isPayment);
//         根据总用户数算出总页数(向上取整)
        int totalPageCount = (int)Math.ceil(new BigDecimal(totalCount).divide(new BigDecimal(pageSize)).doubleValue());

        System.out.println("isPayment:"+isPayment);
        System.out.println("queryProviderId:" + queryProviderId);
        System.out.println("queryProductName:" + queryProductName);
        System.out.println("pageIndex:" + pageIndex);
        System.out.println("供应商id：" + queryProviderId);
        System.out.println("供应商名称：" + queryProductName);
        System.out.println("totalPageCount --> " + totalPageCount);
        System.out.println("totalCount --> " + totalCount);
        System.out.println("pageSize --> " + pageSize);
        System.out.println("currentPageNo --> " + currentPageNo);
        System.out.println("billList --> " + billList);

        model.addAttribute("queryIsPayment",queryIsPayment);
        model.addAttribute("queryProductName",queryProductName);
        model.addAttribute("queryProviderId",queryProviderId);
        model.addAttribute("queryBillRole",billRole);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("currentPageNo",currentPageNo);
        model.addAttribute("billList",billList);
        model.addAttribute("providerList",providerList);

        // 将用户列表存储到session中，方便后续使用
        session.setAttribute("billList",billList);
        session.setAttribute("providerList",providerList);
        return "billlist";
    }

    //  3.2 修改订单信息
    @RequestMapping("/jsp/modifyBill")
    public String modifyBill(long id,Bill bill,HttpSession session){
        System.out.println("修改页面---[id]:"+id);
        Object obj = session.getAttribute("userSession");
        System.out.println("obj的值为"+obj);
        if(obj!=null){
            // 当前登录用户
            User currentUser = (User) obj;
            bill.setModifyBy(currentUser.getId());
        }
        bill.setModifyDate(new Timestamp(System.currentTimeMillis()));
        // bill里面存放修改的信息
        System.out.println("修改用户---[bill]:"+bill);
        int i = billService.updateBill(id, bill);
        System.out.println(i>0?"修改成功":"修改失败");
        return "forward:getBillList";
    }
//
//    //  3.3 添加用户
    @RequestMapping("/jsp/addBill")
    public String addBill(Bill bill,HttpSession session){
        Object obj = session.getAttribute("userSession");
        if(obj!=null){
            User currentUser = (User) obj;
            bill.setCreatedBy(currentUser.getId());
            bill.setCreationDate(new Timestamp(System.currentTimeMillis()));
        }
        System.out.println("addBill 路径的bill:"+bill);
        int i = billService.addBill(bill);
        System.out.println(i>0?"添加成功":"添加失败");
        return "forward:getBillList";
    }

    //  3.4 查看用户信息
    @RequestMapping("/bill/view")
    public String viewBill(String method,int billid,Model model,HttpSession session){
        System.out.println("method:"+method);
        System.out.println("billid:"+billid);
        // 取出查询用户列表时保存在session的billList,以获取该用户信息
        Object obj = session.getAttribute("billList");
        if (obj!=null){
            List<Bill> billList = (List<Bill>) obj;
            for (Bill bill : billList) {
                // 若uid相同，说明查询到用户信息
                if(bill.getId()==billid){
                    model.addAttribute("bill",bill);
                }
            }
        }
        return "billview";
    }
}
